const { ipcRenderer } = require('electron');

Vue.use(ELEMENT);

const app = new Vue({
  el: '#app',
  data: {
    viewId: null,
    fileId: null,
    name: '',
  },
});

ipcRenderer.on('init', async (_event, { viewId, fileId, name, data }) => {
  app.viewId = viewId;
  app.name = name;
  app.fileId = fileId;
  if (data) {
    await editor.minder.importData('json', data);
  }
  listenChange();
});

ipcRenderer.on('toggleTopTab', (_event, tabName) => {
  $(`#${ tabName }`)[0].firstElementChild.click();
});

ipcRenderer.on('showMessage', (_event, { leval, message }) => {
  app.$message({
    message,
    type: leval,
  });
});

ipcRenderer.on('importFile', (_event, { protocol, data }) => {
  switch (protocol) {
    case '.md': protocol = 'markdown'; break;
    case '.json': protocol = 'json'; break;
    case '.txt': protocol = 'text'; break;
  }
  editor.minder.importData(protocol, data);
});

kityminder.data.registerProtocol('xmind', {
  fileDescription: "XMind 格式",
  fileExtension: ".xmind",
  dataType: "blob",
  mineType: "application/octet-stream",
  encode: function (json) {
    return JSON.stringify(json);
  },
  decode: function (local) {
    return JSON.parse(local);
  }
});

ipcRenderer.on('exportFile', async (event, { type, filePath }) => {
  switch (type) {
    case 'md': type = 'markdown'; break;
    case 'txt': type = 'text'; break;
  }
  const data = await editor.minder.exportData(type);
  event.sender.send('saveFile', { filePath, data, type, name: app.name });
});

function listenChange() {
  let saveTimer;
  editor.minder.on("contentchange", async () => {
    clearTimeout(saveTimer);
    saveTimer = setTimeout(async () => {
      const data = await editor.minder.exportData('json');
      ipcRenderer.send('contentChange', { fileId: app.fileId, data });
    }, 3000);
  });
  document.onkeydown = async function (e) {
    var keyCode = e.keyCode || e.which || e.charCode;
    var ctrlKey = e.ctrlKey || e.metaKey;
    if (ctrlKey && keyCode == 83) {
      clearTimeout(saveTimer);
      const data = await editor.minder.exportData('json');
      ipcRenderer.send('contentChange', { fileId: app.fileId, data });
    }
    return false;
  }
}
